package dk.au.cs.bdsi.sms.activities;

import dk.au.cs.bdsi.core.activities.UpdateException;
import dk.au.cs.bdsi.core.representation.Identifier;
import dk.au.cs.bdsi.core.representation.ServiceUri;
import dk.au.cs.bdsi.sms.domain.Sms;
import dk.au.cs.bdsi.sms.domain.SmsStatus;
import dk.au.cs.bdsi.sms.repositories.SmsRepository;
import dk.au.cs.bdsi.sms.representation.SmsRepresentation;

public class UpdateSmsActivity {
	// TODO Make concurrent
	public SmsRepresentation update(Sms sms, ServiceUri requestUri) {
		// Updated message must have status 'NotSeng' or 'Pending'
		if (sms.getStatus() != SmsStatus.NotSent 
				&& sms.getStatus() != SmsStatus.Pending) {
			throw new UpdateException();
		}
		
		// Retrieve current state of the sms
		Identifier id = requestUri.getId();
		Sms currentSms = SmsRepository.current().get(id);
		
		// Ensure sms exists and can be updated
		if (currentSms == null) throw new NoSuchSmsException();
		if (currentSms.getStatus() != SmsStatus.NotSent) throw new UpdateException();
		
		// TODO Perform validity check on user-supplied sms
		
		SmsRepository.current().store(id, sms);
		return SmsRepresentation.createResponseRepresentation(currentSms, requestUri);
	}
}
